package com.controller;

import com.domain.User;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class IndexController {
    @Autowired
    UserService userService;

    /**
     * 首页处理
     * @return
     */
    @RequestMapping("/")
    public String index() {
        return "redirect:/list";
    }

    @RequestMapping("/list")
    public String list(Model model) {
        List<User> userlist =  userService.listUser();
        model.addAttribute("userList",userlist);
        return   "index";
    }

    @RequestMapping("/getById")
    @ResponseBody //注解加上去就不会走视图处理器，这样就不会解析web
    public String getOne(int id) {
        User user =  userService.findUserById(id);
        return   user.toString();
    }

    @RequestMapping("/editUser")
    public String eidtUser(int id,Model model){
        User user =  userService.findUserById(id);
        model.addAttribute("user",user);
        return "editUser";
    }

    @RequestMapping("/updateUser")
    public String updateUser(int id, String name, int age){
        User user = new User(id,name,age);
        int i = userService.updateUser(user);
        return "redirect:/list";
    }


    @RequestMapping("/table")
    public String table(){
        return "table";
    }

    @ResponseBody
    @RequestMapping("/getUserList")
    public Object findUser(int page,int limit){
        Map<String,Object> map = new HashMap<>();

        PageHelper.startPage(page,limit);
        List<User> user = userService.findUser(page);

        PageInfo<User> p  = new PageInfo<User>(user);

//        map.put("p",p);
        map.put("data",user);
        map.put("count",p.getTotal());
        map.put("code",0);
        return map;
    }



}
